package klimuts.periodicals.user.actions;

import java.util.Map;

import klimuts.periodicals.catalog.actions.ShowCatalog;
import klimuts.periodicals.data.DataSource;
import klimuts.periodicals.user.Cart;
import klimuts.periodicals.user.User;

import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;

/**
 * Action put current order to data base.
 * Redirect to login page if user not exists in session.
 * If cart is empty then redirect to {@link ShowCatalog} action.
 *@author Siarhei Klimuts
 */
public class PlaceOrder extends ActionSupport implements SessionAware {
	private Map<String,Object> session;

	public String execute() throws Exception {
		User user=(User)session.get("user");
		Cart cart=(Cart)session.get("cart");
		if (user!=null)
			if ((cart!=null)&&(!cart.isEmpty())) {
				int id=DataSource.addOrder(cart, user);
				if (id>0) {
					addActionMessage(getText("order.success")+" "+getText("order.number")+id);
					cart.clear();
					return "success";
				} else
					return "error";
			} else
				return "input";
		else
			return "login";
	}

	public void setSession(Map<String, Object> session) {
		this.session = session;
	}

}
